# -*- coding: utf-8 -*-
# author: sixmillions
# date: 2022/07/04

import base64
import os
import smtplib
import time
from datetime import datetime
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

import requests
from PIL import Image
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# 常量定义
# DRIVER_PATH = r'D:\OpenSources\chromedriver_win32\chromedriver.exe'

DRIVER_PATH = r'D:\OpenSources\edgedriver_win64\msedgedriver.exe'
WEB_URL = os.environ.get('MRJK_URL')
EMP_NAME = os.environ.get('EMP_NAME')
EMP_ACCOUNT = os.environ.get('EMP_ACCOUNT')
PHONE_NUM = os.environ.get('PHONE_NUM')


def open_browser():
    # browser = webdriver.Chrome(executable_path=DRIVER_PATH)
    # browser = webdriver.Edge(executable_path=DRIVER_PATH)
    chrome_capabilities = {
        "browserName": "chrome",
        "version": "",
        "platform": "ANY",
        "javascriptEnabled": True,
        # "marionette": True,
    }
    browser = webdriver.Remote("http://localhost:3044/wd/hub", desired_capabilities=chrome_capabilities)
    browser.set_page_load_timeout(10)
    browser.get(WEB_URL)
    time.sleep(5)
    # 窗口最大化
    browser.maximize_window()
    time.sleep(1)
    return browser


def login(browser):
    # 点击供应商
    browser.find_element_by_xpath("//*[contains(text(),'供应商')]").click()  # 部分文字
    time.sleep(1)
    # 输入姓名和卡号
    # （会找到两个，是第二个tab页的）
    browser.find_elements_by_xpath("//input[@placeholder='请输入姓名']")[1].send_keys(EMP_NAME)
    browser.find_element_by_xpath("//input[@placeholder='请输入卡号']").send_keys(EMP_ACCOUNT)
    # 点击登录
    print("登录成功判断")
    num = 1
    while True:
        time.sleep(1)
        # 验证码输入
        input_access_code(browser)
        time.sleep(1)
        new_num = do_login(browser)
        num = num + new_num
        if new_num == 0 or num > 5:
            break
    return num


def do_login(browser):
    # span元素不可以点击，父级元素button元素可以点击
    browser.find_element_by_xpath("//span[contains(text(),'填写问卷')]//..").click()
    time.sleep(2)
    # 如果还包含该文字说明跳转失败，说明验证码识别失败，需要再次识别验证码
    list = browser.find_elements_by_xpath("//div[contains(text(),'遵守防疫要求，公司区域内请务必佩戴口罩')]")
    return len(list)


# 识别验证码并输入
def input_access_code(browser):
    img_ele = browser.find_element_by_class_name('van-field__button')
    time.sleep(3)
    browser.get_screenshot_as_file('./screenshot.png')
    left = int(img_ele.location['x'])
    top = int(img_ele.location['y'])
    right = int(img_ele.location['x'] + img_ele.size['width'])
    bottom = int(img_ele.location['y'] + img_ele.size['height'])
    im = Image.open('./screenshot.png')
    im = im.crop((left, top, right, bottom))
    im.save('./access.png')
    # 调用百度ocr接口
    access_code = baidu_ocr(r'./access.png')
    print('识别结果：', access_code)
    # 清空（clear失败：https://blog.csdn.net/sun_977759/article/details/108731881）
    ele = browser.find_element_by_xpath("//input[@placeholder='输入验证码']")
    ele.send_keys(Keys.CONTROL, 'a')
    ele.send_keys(access_code)


def baidu_ocr(img_path):
    print(datetime.now())

    start = time.time()
    # 获取access_token
    # client_id 为官网获取的AK， client_secret 为官网获取的SK
    appid = os.environ.get('BAIDU_OCR_APPID')
    client_id = os.environ.get('BAIDU_OCR_AK')
    client_secret = os.environ.get('BAIDU_OCR_SK')
    print("appid:" + appid)
    print("client_id:" + client_id)
    print("client_secret:" + client_secret)

    token_url = "https://aip.baidubce.com/oauth/2.0/token"
    host = f"{token_url}?grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}"

    response = requests.get(host)
    access_token = response.json().get("access_token")
    print("当前token：", access_token)

    # 调用通用文字识别高精度版接口
    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"
    # 以二进制方式打开图文件
    # 参数image：图像base64编码
    with open(img_path, "rb") as f:
        image = base64.b64encode(f.read())

    body = {
        "image": image,
        "language_type": "auto_detect",
        "detect_direction": "true",
        "paragraph": "true",
        "probability": "true",
    }
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    request_url = f"{request_url}?access_token={access_token}"
    response = requests.post(request_url, headers=headers, data=body)
    content = response.content.decode("UTF-8")
    # 打印调用结果
    print(content)

    end = time.time()
    print(f"Running time: {(end - start):.2f} Seconds")
    res_dict = eval(content)
    print(type(res_dict), res_dict)
    word_list = res_dict['words_result']
    print(type(word_list), word_list)
    if not word_list:
        return '6666'
    return word_list[0]['words']


# 其他操作
def do_other_option(browser):
    time.sleep(1)
    # span元素不可以点击，父级元素button元素可以点击
    browser.find_element_by_xpath("//span[contains(text(),'我承诺')]//..").click()


# 点击我承诺

def do_report(browser):
    # 做题
    time.sleep(2)
    # 5题
    browser.find_element_by_xpath("//span[contains(text(),'全程乘坐私人交通')]").click()
    # 6题
    browser.find_element_by_xpath("//span[contains(text(),'健康状态良好，且不属于政府')]").click()
    # 25题 手机号
    phoneEle = browser.find_element_by_xpath('//*[@id="app"]/div/form/div[31]/div/div[2]/div[2]/div/div/textarea')
    phoneEle.send_keys(Keys.CONTROL, 'a')
    phoneEle.send_keys(PHONE_NUM)
    # 提交
    time.sleep(1)
    browser.find_element_by_xpath("//span[contains(text(),'提交')]//..").click()
    time.sleep(1)
    browser.find_element_by_xpath("//span[@class='van-button__text' and contains(text(),'确认')]//..").click()
    time.sleep(1)
    # 截图
    browser.get_screenshot_as_file(r"./mrjk.png")


def send_mail(subject):
    email_host = 'smtp.163.com'  # 服务器地址 163邮箱"smtp.163.com"  qq邮箱"smtp.qq.com"都需要开通smtp权限
    sender = 'liubw95@163.com'  # 发件人（自己的邮箱）
    password = os.environ.get('MAIL_AUTH_CODE')  # 密码（自己邮箱的登录密码）
    receiver = 'liubw95@163.com'  # 收件人

    msg = MIMEMultipart()
    msg['Subject'] = subject  # 标题
    msg['From'] = 'liubw95@163.com'  # 邮件中显示的发件人别称
    msg['To'] = receiver  # ...收件人...

    mail_msg = '''
    <p>自动化脚本发送!</p>
    <p>无需回复</p>
    <p>截图如下：</p>
    <p><img src="cid:image1"></p>
    '''
    msg.attach(MIMEText(mail_msg, 'html', 'utf-8'))
    # 指定图片为当前目录
    fp = open(r'./mrjk.png', 'rb')
    img = MIMEImage(fp.read())
    fp.close()
    # 定义图片 ID，在 HTML 文本中引用
    img.add_header('Content-ID', '<image1>')
    msg.attach(img)

    smtp = smtplib.SMTP_SSL(email_host, 994)
    smtp.login(sender, password)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()
    print('success')


if __name__ == '__main__':
    print("=============start=============")
    browser = open_browser()
    num = login(browser)
    # 点击我承诺
    if num < 6:
        # 尝试了5次内有成功的
        # 其他操作
        do_other_option(browser)
        # 做题
        do_report(browser)
        subject = time.strftime('%Y-%m-%d', time.localtime()) + ' 自动申报成功'
    else:
        subject = time.strftime('%Y-%m-%d', time.localtime()) + ' 自动申报失败'
    time.sleep(3)
    # 关闭浏览器
    browser.close()
    # 发送邮件
    print("发送邮件")
    send_mail(subject)
    print("==============end==============")
